package com.platform.wechat.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.platform.wechat.common.*;
import com.platform.wechat.entity.WxUser;
import com.platform.wechat.mapper.WxUserMapper;
import com.platform.wechat.service.Wechat114Service;
import org.jdom2.Element;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

/**
 * @author CX
 * @create 2021-07-28 11:57
 */
@Service
public class Wechat114ServiceImpl implements Wechat114Service {

    @Autowired
    private WxUserMapper wxUserMapper;

    /** Logger实例 */
    static final Logger logger = LoggerFactory.getLogger(Wechat114Service.class);

    @Override
    public String Wechat114Msg(Element rootElement) {

        return null;
    }

    @Override
    public JsonBean getUserInfoByCode(String code, HttpSession session) {
        JsonBean jsonBean = new JsonBean(-1, "未知错误", null);
        /**
         * 通过code换取AccessToken(网页授权)
         * openid,根据openid查询数据库（是否存在）
         * 存在直接返回用户基本信息
         * 不存在，继续通过AccessToken+openid换取用户基本信息
         */
        JSONObject jsonObject = Constant.getAccessTokenAndOpenid(code);
        System.err.println(jsonObject+"通过code换取AccessToken(网页授权)");
        if(jsonObject.containsKey("openid")){
            String openid = jsonObject.get("openid").toString();
            WxUser wxUser = wxUserMapper.selectByOpenid(openid);
            if(wxUser == null){
                String access_token = jsonObject.get("access_token").toString();
                wxUser = Constant.getWxUserSnsUserInfo(access_token, openid);
                //insert
            }
            jsonBean.setCode(0);
            jsonBean.setMsg("ok");
            jsonBean.setData(wxUser);
            session.setAttribute("wxUserInfo",wxUser);
        }
        return jsonBean;
    }

    @Override
    public JsonBean getShareData(String targetUrl) {
        //System.err.println("服务层URL:"+targetUrl);
        String noncestr = Commons.getNoncestr();
        Long timestamp = Commons.getTimestamp();
        String jsapiTicket = Constant.getJsapiTicket();
        String sortStr = "jsapi_ticket=JSAPI_TICKET&noncestr=NONCESTR&timestamp=TIMESTAMP&url=URL";
        sortStr = sortStr.replace("JSAPI_TICKET",jsapiTicket).replace("NONCESTR",noncestr).replace("TIMESTAMP",String.valueOf(timestamp)).replace("URL",targetUrl);
        String signature = Sha1.encode(sortStr);
        Map<String, String> map = new HashMap<>();
        map.put("nonceStr",noncestr);
        map.put("timestamp",String.valueOf(timestamp));
        map.put("signature",signature);
        map.put("appId", WechatAPI.APPID);
        //System.err.println("服务层map:"+map);
        return new JsonBean(0,"ok",map);
    }

    @Override
    public String handleWxMsg(Map<String, String> map) {
        String resultXml = "";
        String toUserName = map.get("ToUserName");//开发者微信号
        String fromUserName = map.get("FromUserName");//发送方帐号（一个OpenID）
        String createTime = map.get("CreateTime");//消息创建时间 （整型）
        String msgType = map.get("MsgType");//消息类型，event
        //消息内容
        String content = map.get("Content");
        //事件类型方法
        if(msgType.equals("event")){
            resultXml = hanleEvent(map.get("Event"), toUserName, fromUserName);
            logger.debug(resultXml);
        }else if(msgType.equals("text")){
            resultXml = msgTypeText(content,fromUserName,toUserName);
            logger.debug(resultXml);
        }
        return resultXml;
    }

    @Override
    public JsonBean oAuth(String code) {
        JsonBean jsonBean = new JsonBean(-1, "", null);
        if(code != null){
            JSONObject jsonObject = Constant.getAccessTokenAndOpenid(code);
            jsonBean = new JsonBean(0, "", jsonObject.get("openid").toString());
        }
        return jsonBean;
    }

    @Override
    public JsonBean jsConfig(String url) {
        JsonBean jsonBean = new JsonBean(-1, "", null);
        if(url != null){
            Map<String, String> map = Constant.getSignature(url);
            jsonBean = new JsonBean(0, "", map);
        }
        return jsonBean;
    }

    /**
     * 处理关注事件
     * @param event
     * @param openid
     * @return
     */
    private String hanleEvent(String event, String developerID, String openid){
        WxUser dbWxUser = wxUserMapper.selectByOpenid(openid);
        //事件类型，subscribe(订阅)、unsubscribe(取消订阅)
        if(event.equals("subscribe")){
            WxUser wxGetUserInfo = Constant.getWxUserInfoByUnionID(openid);
            if(dbWxUser == null){
                wxUserMapper.insert(wxGetUserInfo);
            }else{
                wxUserMapper.updateByPrimaryKeyOpenid(wxGetUserInfo);
            }
            return subscribeResultXml(developerID, openid);
        }else if(event.equals("unsubscribe")){
            dbWxUser.setSubscribe(0);
            wxUserMapper.updateByPrimaryKeyOpenid(dbWxUser);
        }
        return "";
    }

    /**
     * 返回关注后文本推送
     * @param developerID
     * @param openid
     * @return
     */
    private String subscribeResultXml(String developerID, String openid){
        String content = "轻松就医，3步挂号！\n" +
                "第一步：【<a href=\""+Constant.oAuth(WechatAPI.URL + "/index.html", Constant.SNSAPI_USERINFO)+"\">注册账号+实名认证</a>】\n" +
                "第二步：【<a href=\""+Constant.oAuth(WechatAPI.URL + "/center.html", Constant.SNSAPI_USERINFO)+"\">个人中心</a>】添加就诊人\n" +
                "第三步：【<a href=\""+Constant.oAuth(WechatAPI.URL + "/index.html", Constant.SNSAPI_USERINFO)+"\">预约挂号</a>】\n" +
                "点击【<a href=\"https://w.url.cn/s/AaOzWFg\">挂号秘籍</a>】查看挂号方法\n" +
                "点击【<a href=\""+Constant.oAuth(WechatAPI.URL + "/index.html", Constant.SNSAPI_USERINFO)+"\">按医院</a>】或【<a href=\""+Constant.oAuth(WechatAPI.URL + "/all.html",Constant.SNSAPI_USERINFO)+"\">按科室</a>】挂号更便捷\n" +
                "点击【<a href=\""+Constant.oAuth(WechatAPI.URL + "/center.html", Constant.SNSAPI_USERINFO)+"\">个人中心</a>】，可添加/修改就诊人信息、查看/取消订单\n" +
                "点击【申诉】提交问题，5个工作日内回复\n" +
                "点击【<a href=\""+Constant.oAuth(WechatAPI.URL + "/help.html", Constant.SNSAPI_USERINFO)+"\">帮助中心</a>】解决注册、挂号、取消等问题";
        return "<xml>\n" +
                "  <ToUserName><![CDATA["+openid+"]]></ToUserName>\n" +
                "  <FromUserName><![CDATA["+developerID+"]]></FromUserName>\n" +
                "  <CreateTime>"+System.currentTimeMillis()/1000+"</CreateTime>\n" +
                "  <MsgType><![CDATA[text]]></MsgType>\n" +
                "  <Content><![CDATA["+content+"]]></Content>\n" +
                "</xml>";
    }

    /**
     * 处理事件类型
     * @param
     * @param openid
     * @return
     */
    private String msgTypeText(String content, String openid, String toUserName){
        long l = System.currentTimeMillis();
        if(content.equals("挂号")){
            return "<xml>\n" +
                    "  <ToUserName>"+openid+"</ToUserName>\n" +
                    "  <FromUserName><![CDATA["+toUserName+"]]></FromUserName>\n" +
                    "  <CreateTime>"+l+"</CreateTime>\n" +
                    "  <MsgType>text</MsgType>\n" +
                    "  <Content>你想咨询什么问题? " +"\n"+
                    "1，我应该怎样挂号？" +"\n"+
                    "2，挂号需要预约吗？提前多久预约？" +"\n"+
                    "3，为什么我挂号失败？" +"\n"+
                    "4，查看我的挂号订单" +"\n"+
                    "5，预约成功可以修改挂号吗？" +"\n"+
                    "6，怎样知道我是否预约成功？" +"\n"+
                    "</Content>\n" +
                    "</xml>\n" +
                    "\n";
        }if(content.equals("预约挂号")){
            return "<xml>\n" +
                    "  <ToUserName>"+openid+"</ToUserName>\n" +
                    "  <FromUserName><![CDATA["+toUserName+"]]></FromUserName>\n" +
                    "  <CreateTime>"+l+"</CreateTime>\n" +
                    "  <MsgType>text</MsgType>\n" +
                    "  <Content>请问您遇到了什么问题？" +"\n"+
                    "【挂号】" +"\n"+
                    "【预约挂号】" +"\n"+
                    "【预约】" +"\n"+
                    "如果未匹配到想要的回复，可回复问题关键字" +"\n"+
                    "</Content>\n" +
                    "</xml>\n" +
                    "\n";
        }if(content.equals("预约")){
            return "<xml>\n" +
                    "  <ToUserName>"+openid+"</ToUserName>\n" +
                    "  <FromUserName><![CDATA["+toUserName+"]]></FromUserName>\n" +
                    "  <CreateTime>"+l+"</CreateTime>\n" +
                    "  <MsgType>text</MsgType>\n" +
                    "  <Content>你想咨询什么问题? " +"\n"+
                    "1，我应该怎样挂号？" +"\n"+
                    "2，挂号需要预约吗？提前多久预约？" +"\n"+
                    "3，为什么我挂号失败？" +"\n"+
                    "4，查看我的挂号订单" +"\n"+
                    "5，预约成功可以修改挂号吗？" +"\n"+
                    "6，怎样知道我是否预约成功？" +"\n"+
                    "</Content>\n" +
                    "</xml>\n" +
                    "\n";
        }
        return "<xml>\n" +
                "  <ToUserName>"+openid+"</ToUserName>\n" +
                "  <FromUserName><![CDATA["+toUserName+"]]></FromUserName>\n" +
                "  <CreateTime>"+l+"</CreateTime>\n" +
                "  <MsgType>text</MsgType>\n" +
                "  <Content>没有找到您要的问题！请输入问题关键字！</Content>\n" +
                "</xml>\n" +
                "\n";
    }

    /**
     * 添加
     * @param wxUser
     * @return
     */
    @Override
    public JsonBean addWxUser(WxUser wxUser) {
        JsonBean jsonBean = new JsonBean(-1,"操作失败!",null);
        int i = wxUserMapper.insertSelective(wxUser);
        if(i>0){
            jsonBean.setCode(0);
            jsonBean.setMsg("ok");
        }
        return jsonBean;
    }

    /**
     * 删除
     * @param id
     * @return
     */
    @Override
    public JsonBean deleteWxUser(Integer id) {
        JsonBean jsonBean = new JsonBean(-1,"操作失败!",null);
        int i = wxUserMapper.deleteByPrimaryKey(id);
        if(i>0){
            jsonBean.setCode(0);
            jsonBean.setMsg("ok");
        }
        return jsonBean;
    }

    /**
     * 修改
     * @param wxUser
     * @return
     */
    @Override
    public JsonBean updateWxUser(WxUser wxUser) {
        JsonBean jsonBean = new JsonBean(-1,"操作失败!",null);
        int i = wxUserMapper.updateByPrimaryKeySelective(wxUser);
        if(i>0){
            jsonBean.setCode(0);
            jsonBean.setMsg("ok");
        }
        return jsonBean;
    }

    /**
     * 根据id查询
     * @param id
     * @return
     */
    @Override
    public JsonBean selectById(Integer id) {
        return new JsonBean(0,"ok",wxUserMapper.selectByPrimaryKey(id));
    }

    /**
     * 查询全部
     * @return
     */
    @Override
    public JsonBean selectWxUserList() {
        return new JsonBean(0,"ok",wxUserMapper.selectWxUserList());
    }

}
